package bungaeting.net.client.android.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.util.Log;
import bungaeting.net.client.android.utils.JsonUtil;

public class HttpRequestor extends Requestor {
	
	protected String makRequestURL(String serviceId){
		return "http://runafter8.iptime.org/bungaeting/";
	}

	@Override
	public Response doRequest(Request request) {
		BufferedReader reader = null;
		OutputStreamWriter writer = null;
		String strResponse = "";
		String requestData = JsonUtil.toJSonString(request.toMap());
		String postRequestData = "requestData=" + URLEncoder.encode(requestData);
		Log.d("TEST", "requestData " + requestData);
		Log.d("TEST", "postRequestData " + postRequestData);
		try {
			URL url = new URL(makRequestURL(request.getServiceId()));
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			urlConnection.setRequestProperty("Content-Length", Integer.toString(postRequestData.length()));
			urlConnection.setDoOutput(true);

			writer = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
			writer.write(postRequestData);
	        writer.flush();
			
			reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null){
				strResponse += line + "\n";
			}
		
			Log.d("TEST", "strResponse " +  strResponse);
			Log.d("TEST", "strResponse Map " +  JsonUtil.toMap(strResponse));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (writer != null)
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		return this.createResponse(request, JsonUtil.toMap(strResponse));
	}

}
